package com.dynamicdatasource.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.dynamicdatasource.annotation.DataSource;
import com.dynamicdatasource.config.DynamicDataSourceContextHolder;

@Aspect
@Order(-1)// 该切面应当先于 @Transactional 执行
@Component
public class DataSourceAspect {
	/**
     * 切换数据源
     * @param point
     * @param dataSource
     */
    @Before("@annotation(dataSource))")
    public void switchDataSource(JoinPoint point, DataSource dataSource) {
    	DynamicDataSourceContextHolder.setDataSource(dataSource.value());;
    }
    
    /**
     * 重置数据源
     * @param point
     * @param dataSource
     */
    @After("@annotation(dataSource))")
    public void restoreDataSource(JoinPoint point, DataSource dataSource) {
        // 将数据源置为默认数据源
        DynamicDataSourceContextHolder.clearDataSource();
    }
}
